package com.ruoyi.web.controller.video;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.Msg;
import com.ruoyi.web.controller.video.Utils.SendKs;
import com.ruoyi.web.controller.video.Utils.TableTabs;
import com.ruoyi.web.controller.video.Utils.TakeVideo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.constant.RoomInfoGetTypeEnum;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.msg.KuaishouDanmuMsg;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.msg.KuaishouGiftMsg;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.msg.KuaishouLikeMsg;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.msg.KuaishouRoomStatsMsg;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.protobuf.PayloadTypeOuterClass;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.protobuf.WebGiftFeedOuterClass;
import tech.ordinaryroad.live.chat.client.commons.base.msg.ICmdMsg;
import tech.ordinaryroad.live.chat.client.commons.base.msg.IMsg;
import tech.ordinaryroad.live.chat.client.commons.client.enums.ClientStatusEnums;
import tech.ordinaryroad.live.chat.client.kuaishou.client.KuaishouLiveChatClient;
import tech.ordinaryroad.live.chat.client.kuaishou.config.KuaishouLiveChatClientConfig;
import tech.ordinaryroad.live.chat.client.kuaishou.listener.IKuaishouMsgListener;
import tech.ordinaryroad.live.chat.client.kuaishou.netty.handler.KuaishouBinaryFrameHandler;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/video/ks")
public class VideoController {

    Map<String, List<WebGiftFeedOuterClass.WebGiftFeed>> map = new HashMap<>();

    static Object lock = new Object();
    KuaishouLiveChatClient res;

    Map<String, SendKs> clinets = new HashMap<>();

    Map<String, List<String>> userRoom = new HashMap<>();

    Map<String, Date> userClick = new HashMap<>();

    @PostMapping("/addVideo")
    public void addVideo(@RequestBody Msg msg, @AuthenticationPrincipal UserDetails user) {
        LoginUser loginUser =  (LoginUser)user;
        SysUser sysUser = loginUser.getUser();

       SendKs sendKs = new SendKs();
       sendKs.takeKsMsg(msg.getRoomId(),sysUser,msg.getCookie());
       clinets.put(msg.getRoomId(),sendKs);

       if(userRoom.get(sysUser.getUserId()+"") == null){
           List<String> list = Lists.newArrayList();
           list.add(msg.getRoomId());
           userRoom.put(sysUser.getUserId()+"",list);
       }else{
           List<String> list = userRoom.get(sysUser.getUserId()+"");
           list.add(msg.getRoomId());
           userRoom.remove(sysUser.getUserId()+"");
           userRoom.put(sysUser.getUserId()+"",list);
       }


    }


    public static void main(String[] args) {
        Map<String, List<String>> userRoom = new HashMap<>();
        System.out.println(userRoom.get("1")==null);
    }

    @GetMapping(value = "/startVideo/{roomId}")
    public AjaxResult startVideo(@PathVariable("roomId") String roomId) {

        try {
            clinets.get(roomId).startSocket();
            return AjaxResult.success(200);
        }catch (Exception e){
            clinets.remove(roomId);
            return AjaxResult.success(500);
        }
    }


    @GetMapping(value = "/stopVideo/{roomId}")
    public void stopVideo(@PathVariable("roomId") String roomId) {
        clinets.get(roomId).stopSocket();
    }


    @GetMapping(value = "/getStatus/{roomId}")
    public AjaxResult getStatus(@PathVariable("roomId") String roomId) {

        return AjaxResult.success(clinets.get(roomId).getStatus());
    }


    //此方法暂时废弃
    @SneakyThrows
    @PostMapping(value = "/setCookie")
    public void setCookie(@RequestBody Msg msg, @AuthenticationPrincipal UserDetails user) {
        LoginUser loginUser =  (LoginUser)user;
        SysUser sysUser = loginUser.getUser();
        List<String> roomIds = userRoom.get(sysUser.getUserId()+"");
        for(String roomId : roomIds){
            clinets.get( roomId ).setCookie(msg.getCookie());
            clinets.get( roomId ).startSocket();
        }
    }



    @GetMapping(value = "/sendNoindy")
    public AjaxResult getStatus(@AuthenticationPrincipal UserDetails user) {
        LoginUser loginUser =  (LoginUser)user;
        SysUser sysUser = loginUser.getUser();
        userClick.remove(sysUser.getUserId()+"");
        userClick.put(sysUser.getUserId()+"",new Date());
        return AjaxResult.success();
    }


    @Scheduled(fixedRate = 600000)
    public void sayHello() {
        System.out.println("开始轮询");
        Iterator<Map.Entry<String, Date>> iterator = userClick.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Date> entry = iterator.next();
            String key = entry.getKey();
            Date startDate = entry.getValue();
            Date endDate = new Date();
            // 计算两个日期之间的毫秒差值
            long differenceInMilliSeconds = endDate.getTime() - startDate.getTime();
            // 将毫秒差值转换为秒
            long differenceInSeconds = TimeUnit.MILLISECONDS.toSeconds(differenceInMilliSeconds);

            if(differenceInSeconds>60){
               List<String> rooms = userRoom.get(key);
               for(int i = 0; i< rooms.size(); i++){
                   clinets.get(rooms.get(i)).stopSocket();
               }
            }

        }
    }




}
